<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/1/24
 * Time: 21:25
 */

namespace app\index\controller;


use app\common\utils\WeChatUtils;
use app\index\logic\UserLogic;
use think\Config;
use think\Controller;

class WeChat extends Controller
{
    //网页授权回调
    public function html_return(){
        session(null);//清空
        $file = 'log';
        $fp = fopen($file, 'a+');
        $code = $this->request->param('code');
        $state = $this->request->param('state');
        if('' != $state && strstr($state,"#")) {
            $state = explode('#',$state);
            $state = $state[0];
        }
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        $result = $utils->getHtmlAccessToken($code);
        if(!$result){
            flock($fp, LOCK_UN);
            fclose($fp);
//            var_dump('getHtmlAccessToken');
            return;
        }
        session('openid',$result->openid);//存入sessoin
        //获取用户详细信息
        $userInfo = $utils->getUserInfo($result->access_token,$result->openid);
        $logic = new UserLogic();
        $user = $logic->saveOrUpdateUser($result->openid,$userInfo);
        session('user',$user);//存入sessoin
        if(!empty($state)){
            $result = $logic->bindNote($result->openid,$state);
            if($result['status'] == 1) {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . "/index/index/detail?user_note_id=" . $result['data'];
                header("Location: " . $url);
            }
            exit;
        }

        $this->redirect('index/index');
    }

    public function bindNote(){
        $note_id = $this->request->param('note_id');
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        $utils->getUserCode($note_id);
    }
}